//
//  PhotoBroswerController.swift
//  sinaWeibo
//
//  Created by 张国梁 on 16/4/16.
//  Copyright © 2016年 CoderGL. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
import SVProgressHUD


private let cellIdendifier = "photoBroswerCellIdendifier"

class PhotoBroswerController: UIViewController {
    
    
    var pictureURLs: [NSURL]?
    var currentIndex: Int = 0{
        didSet{
            currentNumberLabel.hidden = (pictureURLs!.count == 1)
            currentNumberLabel.text = "\(currentIndex+1)/\(pictureURLs!.count)"
            
            let indexPath = NSIndexPath(forItem: currentIndex, inSection: 0)
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Right, animated: false)
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.blackColor()
        
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        view.addSubview(currentNumberLabel)
        
        collectionView.snp_updateConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        closeBtn.snp_updateConstraints { (make) in
            make.left.equalTo(margin)
            make.bottom.equalTo(-margin)
            make.width.equalTo(60)
            make.height.equalTo(25)
        }
        
        saveBtn.snp_updateConstraints { (make) in
            make.right.equalTo(-margin)
            make.bottom.equalTo(-margin)
            make.size.equalTo(closeBtn)
        }
        
        currentNumberLabel.snp_updateConstraints { (make) in
            make.top.equalTo(view).offset(20)
            make.centerX.equalTo(view)
        }
    }
    
    
    func close()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    func save()
    {
        // 取出当前的图片
        let cell = collectionView.visibleCells().last as! PhotoBroswerCell
        
        // 保存图片
        if let image = cell.imageView.image {
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(PhotoBroswerController.image(_:didFinishSavingWithError:contextInfo:)), nil)
        }
        
    }
    
    func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject?) -> Void {
        if didFinishSavingWithError != nil {
            
            SVProgressHUD.showErrorWithStatus("保存失败")
            return
        }
        SVProgressHUD.showSuccessWithStatus("保存成功")
    }
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(screenW, screenH)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        let collectionView = UICollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.pagingEnabled = true
        
        
        collectionView.registerClass(PhotoBroswerCell.self, forCellWithReuseIdentifier: cellIdendifier)
        
        return collectionView
    }()
    
    private lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("关闭", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.darkGrayColor()
        
        btn.addTarget(self, action: #selector(PhotoBroswerController.close), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    private lazy var saveBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.darkGrayColor()
        
        btn.addTarget(self, action: #selector(PhotoBroswerController.save), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()

    private lazy var currentNumberLabel: UILabel = {
        let label = UILabel.label(UIColor.whiteColor(), fontSize: 14)
        return label
    }()
}


extension PhotoBroswerController: UICollectionViewDataSource, UICollectionViewDelegate, PhotoBroswerCellDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdendifier, forIndexPath: indexPath) as! PhotoBroswerCell
        
        cell.delegate = self
        cell.picURL = pictureURLs![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        let currenIndexPath = collectionView.indexPathsForVisibleItems().last
        
        currentNumberLabel.text = "\(currenIndexPath!.row + 1)/\(pictureURLs!.count)"
        
    }
    
    func photoBroswerCellDidClickPhoto(cell: PhotoBroswerCell) {
        close()
    }
}





protocol PhotoBroswerCellDelegate: NSObjectProtocol {
    
    func photoBroswerCellDidClickPhoto(cell: PhotoBroswerCell) -> Void;
}


class PhotoBroswerCell: UICollectionViewCell {
    
    var delegate: PhotoBroswerCellDelegate?
    
    var picURL: NSURL?{
        didSet{
            resetScrollView()
            activity.startAnimating()
            imageView.sd_setImageWithURL(picURL, placeholderImage: nil, options: SDWebImageOptions(rawValue: 0), progress: { (current, total) in
//                let progress = Float(current)/Float(total)
                }) { (image, error, _, _) in
                    self.activity.stopAnimating()
                    if image == nil {
                        return
                    }
                    
                    self.calculatePosition(image)
            }
        }
    }
    
    private func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
        scrollView.zoomScale = 0
    }
    
    private func calculatePosition(image: UIImage) {
        let size = self.calculateSize(image)
        self.imageView.frame = CGRect(origin: CGPointZero, size: size)
        if size.height < screenH {
            
            var insetY = (screenH - size.height) * 0.5
            var insetX = (screenW - size.width) * 0.5
            insetY = insetY < 0 ? 0 : insetY
            insetX = insetX < 0 ? 0 : insetX
            
            scrollView.contentInset = UIEdgeInsetsMake(insetY, insetX, insetY, insetX)
            scrollView.contentSize = CGSizeZero
        } else {
            scrollView.contentSize = size
        }
    }
    
    private func calculateSize(image: UIImage) -> CGSize {
            let scale = screenW / image.size.width
            let picHeight = image.size.height * scale
            
            let newSize = CGSizeMake(screenW, picHeight)
            return newSize
    }
    
    
    func photoDidClick() {
        delegate?.photoBroswerCellDidClickPhoto(self)
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        scrollView.addSubview(activity)
        
        scrollView.snp_updateConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        activity.center = screenCenter
    }
    
    
    
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        scrollView.delegate = self
        return scrollView
    }()
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PhotoBroswerCell.photoDidClick)))
        return imageView
    }()
    
    private lazy var activity: UIActivityIndicatorView = {
        let ac = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        ac.hidesWhenStopped = true
        return ac
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
extension PhotoBroswerCell: UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        var insetY = (screenH - view!.frame.size.height) * 0.5
        var insetX = (screenW - view!.frame.size.width) * 0.5
        
        insetX = insetX < 0 ? 0 : insetX
        insetY = insetY < 0 ? 0 : insetY
        
        scrollView.contentInset = UIEdgeInsetsMake(insetY, insetX, insetY, insetX)
        scrollView.contentSize = view!.frame.size
    }
}